package com.surprise.bweb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.surprise.base.util.Md5Utils;
import com.surprise.biz.utils.UserSessionUtils;
import com.surprise.bweb.aspect.UserAuth;
import com.surprise.bweb.bo.CommonRes;
import com.surprise.bweb.bo.EditUploadRes;
import com.surprise.bweb.bo.UploadRes;
import com.surprise.bweb.manager.SessionManager;
import com.surprise.bweb.utils.ResponseUtils;
import com.surprise.db.entity.BUser;
import com.surprise.ods.aliyun.OSSService;

/**
 * SurpriseUploadController.java
 * @author nick
 * @since 2015年8月18日
 */
@Controller
@RequestMapping(value = "/api", produces={"application/json"})
public class SurpriseUploadController {
	@Autowired
	private OSSService ossService;
	
	@Autowired
	private SessionManager sessionManager;
	
	@RequestMapping("/upload/{type}")
	@ResponseBody
	@UserAuth
	public CommonRes upload(@PathVariable("type") int type, @RequestParam("filename") MultipartFile file) {
		BUser user = sessionManager.getCurrentUser();
		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();
				String name = Md5Utils.md5(bytes);
				String url = ossService.put(
						UserSessionUtils.userImageKey(user.getId()), name
								+ ".jpg", bytes);
				return new UploadRes().setData(new UploadRes.Result()
						.setUrl(url));
			} catch (Exception e) {
				return ResponseUtils.exception(e);
			}
		}
		return ResponseUtils.errorMsg("空文件");
	}
	
	@RequestMapping("/editUpload")
	@UserAuth
	public EditUploadRes editUpload(@RequestParam("filename") MultipartFile file) {
		BUser user = sessionManager.getCurrentUser();
		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();
				String name = Md5Utils.md5(bytes);
				String url = ossService.put(UserSessionUtils.userImageKey(user.getId()), name + ".jpg", bytes);
				return new EditUploadRes(url, "SUCCESS");
			} catch(Exception e) {
				return new EditUploadRes("", "FAIL");
			}
		}
		return new EditUploadRes("", "FAIL");
	}
}
